<html>
<head><title>My Test Extension Options</title>
<script type="text/javascript" src="jquery.min.1.6.1.js"></script>
<script type="text/javascript" src="jquery-ui.min.1.8.13.js"></script>
</head>
<script type="text/javascript">

function status(message) {
  $("#status").html(message);
  setTimeout(function() {
      $("#status").html("");
      }, 1500);
}

// Saves options to localStorage.
function save_options() {
  var selected = $(".ui-selected");
  console.log(selected.data("model"));
  localStorage["model"] = JSON.stringify(selected.data("model"));
  localStorage["host"] = $("#host").val();

  // Update status to let user know options were saved.
  status("Options Saved.");
}

// Restores select box state to saved value from localStorage.
function restore_options(models) {
  models.forEach(function(model) {
      console.log(model);
      var li = '<li class="ui-widget-content" id="' + model.id +'">' + model.id + ' ' + model.name + ' - Categories: ' + model.categories + ' ' + '</li>';
      console.log(li);
      $("#models").append($(li).data("model", model));
      });
  $("#models").selectable();

  var currentstr = localStorage["model"];
  console.log(currentstr);
  if (!currentstr) {
    return;
  }
  current = JSON.parse(currentstr);
  console.log(current.id);
  $("#" + current.id).addClass("ui-selected").siblings().removeClass("ui-selected");
}

function getModels() {
  $("#host").change(function() {
      localStorage["host"] = $("#host").val();
      getModels();
  });
  var host = localStorage["host"];
  if (host) {
      $("#host").val(host);
      $.ajax({
        url: host + "models/get",
        dataType: "json",
        success: function(models){
          console.log(models);
          restore_options(models);
        }
      });
  } else {
    status("You need to set the host first");
  }
}
</script>
<style>
	#feedback { font-size: 1.4em; }
	#models .ui-selecting { background: #FECA40; }
	#models .ui-selected { background: #F39814; color: white; }
	#models { list-style-type: none; margin: 0; padding: 0; width: 60%; }
	#models li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
</style>
<body onload="getModels()">
<p>Host:</p>
<input type="text" id="host"></input>    
<p>Active Model:</p>
<ol id="models">
</ol>
<br>
<button onclick="save_options()">Save</button>
<div id="status"></div>
</body>
</html>